﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;

namespace ModelClassLibrary.historymodel
{
    public class HistoryWebModel
    {
        public HistoryWebModel()
        {
            //Application.Current.Suspending += (s, e) =>
            //{
            //    e.SuspendingOperation.GetDeferral();
            //};
            var task = Read(DateTime.Now);
        }

        public List<TimeHistory> HistoryTime
        {
            set;
            get;
        } = new List<TimeHistory>();

        public static HistoryWebModel HistoryWeb
        {
            set
            {
                _historyWeb = value;
            }
            get
            {
                return _historyWeb ?? (_historyWeb = new HistoryWebModel());
            }
        }

        public async Task Storage()
        {
            try
            {
                StorageFolder folder = null;
                try
                {
                    folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(_folder);

                }
                catch (Exception)
                {
                    folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(_folder);
                }
                foreach (var temp in HistoryTime.Where(temp => temp.Check))
                {
                    string str = History.ConvertTimeStr(temp.Time);
                    StorageFile file = await folder.CreateFileAsync(str, CreationCollisionOption.ReplaceExisting);
                    str = temp.ToString();
                    await FileIO.WriteTextAsync(file, str);
                }
            }
            catch
            {

            }
        }

        public void Add(History history)
        {
            var time = HistoryTime.
                FirstOrDefault(temp => temp.Time.Year == history.Time.Year &&
                                       temp.Time.Month == history.Time.Month &&
                                       temp.Time.Day == history.Time.Day);
            if (time != null)
            {
                time.HistoryWeb.Add(history);
                time.Check = true;
            }
            else
            {
                HistoryTime.Add(new TimeHistory()
                {
                    Check = true,
                    Time = history.Time,
                    HistoryWeb = new List<History>()
                    {
                        history
                    }
                });
            }
        }



        public async Task Read(DateTime time)
        {
            string str = History.ConvertTimeStr(time);

            try
            {
                StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(_folder);
                StorageFile file = await folder.GetFileAsync(str);
                using (StreamReader stream = new StreamReader(
                    await file.OpenStreamForReadAsync()))
                {
                    str = stream.ReadToEnd();
                }
                var history = TimeHistory.Unencoding(str);
                var historyWeb = HistoryTime.
                    FirstOrDefault(temp => temp.Time.Year == history.Time.Year &&
                                           temp.Time.Month == history.Time.Month &&
                                           temp.Time.Day == history.Time.Day);
                if (historyWeb != null)
                {
                    historyWeb.HistoryWeb.AddRange(history.HistoryWeb);
                }
                else
                {
                    HistoryTime.Add(history);
                }
            }
            catch(FileNotFoundException)
            {
            }
        }

        private string _folder = "history";

        private static HistoryWebModel _historyWeb;
    }
}